const express = require('express');
const path = require('path');
const fs = require('fs');
const PdfConverter = require('./converter');
const config = require('./config');

const app = express();
const port = process.env.PORT || 9421;

app.use(express.static(path.join(__dirname, 'dist')))

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'templates')));

// 确保必要的目录存在
const ensureDirectory = (dir) => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
};

// 初始化目录
ensureDirectory(config.defaultSourceDir);
ensureDirectory(config.defaultTargetDir);

// 主页
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'templates', 'index.html'));
});

// 获取当前配置
app.get('/config', (req, res) => {
  res.json({
    sourceDir: config.defaultSourceDir,
    targetDir: config.defaultTargetDir,
    resolution: config.resolution,
    namingRules: config.namingRules
  });
});

// 更新配置
app.post('/config', (req, res) => {
  if (req.body.sourceDir) {
    config.defaultSourceDir = req.body.sourceDir;
    ensureDirectory(config.defaultSourceDir);
  }
  
  if (req.body.targetDir) {
    config.defaultTargetDir = req.body.targetDir;
    ensureDirectory(config.defaultTargetDir);
  }
  
  if (req.body.resolution) {
    config.resolution = parseInt(req.body.resolution);
  }

  if(req.body.namingRules) {
    config.namingRules = req.body.namingRules
  }
  res.json({ success: true});
});

// 开始转换
app.post('/convert', async (req, res) => {
  const sourceRoot = req.body.sourceDir || config.defaultSourceDir;
  const targetRoot = req.body.targetDir || config.defaultTargetDir;
  
  // 验证目录是否存在
  if (!fs.existsSync(sourceRoot)) {
    return res.status(400).json({ 
      success: false, 
      error: `源文件夹不存在: ${sourceRoot}` 
    });
  }
  
  // 创建转换器实例
  const converter = new PdfConverter();
  
  try {
    const result = await converter.batchConvert(sourceRoot, targetRoot);
    
    if (result.success) {
      res.json({
        success: true,
        message: '转换完成!',
        stats: {
          pdfs: result.totalPdfs,
          pages: result.totalPages,
          images: result.totalImages
        }
      });
    } else {
      res.status(500).json({
        success: false,
        error: result.error || '转换过程中出错'
      });
    }
  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message || '转换过程中出错'
    });
  }
});

// 获取日志
app.get('/log', (req, res) => {
  try {
    if (fs.existsSync(config.logFile)) {
      const logContent = fs.readFileSync(config.logFile, 'utf-8');
      res.send(logContent);
    } else {
      res.send('暂无日志记录');
    }
  } catch (error) {
    res.status(500).send('读取日志失败');
  }
});

// 启动服务器
app.listen(port, async () => {
  console.log(`请手动访问: http://localhost:${port}`);
});